<template>
  <SectionContainer class="u-p20">
    <!-- 标题 -->
    <SectionTitle>广告主账户管理</SectionTitle>

    <!-- 筛选 start -->
    <el-form
      class="m-filter"
      inline
    >
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择账户"
          v-model="filter.account"
        >
          <el-option
            v-for="(item, index) in accountOptions"
            :key="index"
            :value="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择公司名称"
          v-model="filter.company"
        >
          <el-option
            v-for="(item, index) in companyOptions"
            :key="index"
            :value="item.company"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择角色"
          v-model="filter.roleId"
        >
          <el-option
            v-for="(item, index) in roleOptions"
            :key="index"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          size="small"
          placeholder="请选择账户状态"
          v-model="filter.status"
        >
          <el-option
            label="全部状态"
            :value="0"
          >
          </el-option>
          <el-option
            label="启用"
            :value="2"
          >
          </el-option>
          <el-option
            label="停用"
            :value="1"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="search"
        >查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 筛选 end -->

    <!-- 表格 start -->
    <TableFull
      :data="tableData"
      :total="tableTotal"
      :current-page="page.pageNo"
      @current-change="currentChange"
      @size-change="sizeChange"
      @selection-change="tableSelectionChange"
    >
      <el-form
        class="m-filter"
        inline
        slot="handle"
      >
        <el-form-item v-permission="['account_advertiser_add']">
          <el-button
            size="small"
            @click="$router.push({
              name: 'account-advertiser-basic',
              query: {
                action: 'create',
                userType: 1,
                query: {
                  ...page
                }
              }
            })"
          >
            新增
          </el-button>
        </el-form-item>
        <el-form-item v-permission="['account_advertiser_setProfitRatio']">
          <el-button
            size="small"
            @click="openEarningsMulti"
          >设置账户盈利比</el-button>
        </el-form-item>
        <el-form-item v-permission="['account_advertiser_setExposureRatio']">
          <el-button
            size="small"
            @click="openExposureMulti"
          >设置账户曝光率比</el-button>
        </el-form-item>
      </el-form>
      <template slot="column">
        <el-table-column
          :resizable="false"
          align="center"
          type="selection"
          width="40"
        ></el-table-column>
        <el-table-column
          :resizable="false"
          align="center"
          width="130"
          label="操作"
        >
          <template slot-scope="scope">
            <el-tooltip
              v-permission="['account_advertiser_edit']"
              effect="dark"
              placement="top"
              content="编辑"
              v-if="['启用', '审核拒绝', '资质待提交'].includes(scope.row.accountStatus)"
            >
              <i
                class="u-table-handle iconfont iconfont-5"
                @click="$router.push({
                  name: 'account-advertiser-basic',
                  query: {
                    action: 'edit',
                    userType: 1,
                    userId: scope.row.userId,
                    query: {
                      ...page
                    }
                  }
                })"
              ></i>
            </el-tooltip>
            <el-tooltip
              v-permission="['account_advertiser_view']"
              effect="dark"
              placement="top"
              content="查看"
            >
              <i
                class="u-table-handle iconfont iconfont-6"
                @click="$router.push({
                  name: 'account-advertiser-basic',
                  query: {
                    action: 'detail',
                    userType: 1,
                    userId: scope.row.userId,
                    query: {
                      ...page
                    }
                  }
                })"
              ></i>
            </el-tooltip>
            <el-tooltip
              v-permission="['account_advertiser_resetPwd']"
              effect="dark"
              placement="top"
              content="重置密码"
            >
              <i
                class="u-table-handle iconfont iconfont-11"
                @click="handleResetPassword(scope.row.userId)"
              ></i>
            </el-tooltip>
            <el-tooltip
              v-permission="['account_advertiser_delete']"
              v-if="scope.row.status === 1"
              effect="dark"
              placement="top"
              content="删除账户"
            >
              <i
                class="u-table-handle el-icon-circle-close"
                @click="openDeleteAccount([scope.row.userId])"
              ></i>
            </el-tooltip>
            <el-tooltip
              v-if="scope.row.userId !== user.userId && scope.row.accountStatus === '启用'"
              v-permission="['account_advertiser_enterAccount']"
              effect="dark"
              placement="top"
              content="进入账户"
            >
              <i
                class="u-table-handle iconfont iconfont-36"
                @click="handleEnterAccount(scope.row.userId)"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          :resizable="false"
          align="center"
          v-for="(item, index) in tableColumn"
          :key="index"
          :prop="item.prop"
          :sortable="item.sortable"
          :width="item.width"
          :label="item.label"
        >
          <template slot-scope="scope">
            <!-- 历史盈利比 -->
            <el-popover
              v-if="item.prop === 'profitPercentage'"
              placement="top"
              width="320"
              trigger="click"
            >
              <el-table
                :data="profitHistoryData"
                :max-height="300"
              >
                <el-table-column
                  :resizable="false"
                  width="200"
                  property="createTime"
                  label="日期"
                ></el-table-column>
                <el-table-column
                  :resizable="false"
                  width="120"
                  property="profitPercentage"
                  label="历史盈利比"
                >
                  <template slot-scope="scope">{{scope.row[item.prop] + '%'}}</template>
                </el-table-column>
              </el-table>
              <span
                slot="reference"
                class="c-text-high u-cursor"
                @click="fetchAccountGetEarnings(scope.row.userId)"
              >{{scope.row.profitPercentage + '%'}}</span>
            </el-popover>
            <!-- 历史曝光数比 -->
            <el-popover
              v-else-if="item.prop === 'displayPercentage'"
              placement="top"
              width="320"
              trigger="click"
            >
              <el-table
                :data="exposureHistoryData"
                :max-height="300"
              >
                <el-table-column
                  :resizable="false"
                  width="200"
                  property="createTime"
                  label="日期"
                ></el-table-column>
                <el-table-column
                  :resizable="false"
                  width="120"
                  property="displayPercentage"
                  label="历史曝光数比"
                >
                  <template slot-scope="scope">{{scope.row[item.prop] + '%'}}</template>
                </el-table-column>
              </el-table>
              <span
                slot="reference"
                class="c-text-high u-cursor"
                @click="fetchAccountGetExposure(scope.row.userId)"
              >{{scope.row.displayPercentage + '%'}}</span>
            </el-popover>
            <!-- 账户状态 -->
            <template v-else-if="item.prop === 'auditStatus'">
              <el-popover
                v-if="scope.row.accountStatus !== '资质待提交'"
                placement="top"
                width="350"
                trigger="hover"
              >
                <AuditStatus>
                  <AuditStatusItem
                    v-if="scope.row.auditMap.internalAudit"
                    :title="getInnerStatusTitle(scope.row.auditMap.internalAudit)"
                    :content="scope.row.auditMap.internalAudit"
                  ></AuditStatusItem>
                  <AuditStatusItem
                    v-if="scope.row.auditMap.waitAudit"
                    title="<i class='el-icon-question c-hint-warn'></i> 待审核平台（不可在以下平台投放）"
                    :content="scope.row.auditMap.waitAudit"
                  ></AuditStatusItem>
                  <AuditStatusItem
                    v-if="scope.row.auditMap.passAudit"
                    title="<i class='el-icon-success c-hint-succ'></i> 已通过审核平台（可在以下平台投放）"
                    :content="scope.row.auditMap.passAudit"
                  ></AuditStatusItem>
                  <AuditStatusItem
                    v-if="scope.row.auditMap.unPassAudit"
                    title="<i class='el-icon-warning c-hint-error'></i> 未通过审核平台（不可在以下平台投放）"
                    :content="scope.row.auditMap.unPassAudit"
                  ></AuditStatusItem>
                </AuditStatus>
                <span slot="reference">{{scope.row.accountStatus}} <i class="c-text-high u-cursor el-icon-warning"></i></span>
              </el-popover>
              <template v-else>{{scope.row.accountStatus}}</template>
            </template>

            <!-- 是否启用 -->
            <template v-else-if="item.prop === 'switch'">
              <el-switch
                v-if="[1, 2].includes(scope.row.status)"
                @change="openStatus([scope.row.userId], scope.row.status === 1 ? 2 : 1)"
                :value="scope.row.status"
                :active-value="2"
                :inactive-value="1"
              ></el-switch>
            </template>
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
      </template>
    </TableFull>

    <!--设置账户盈利比-->
    <DialogRatio
      title="设置账户盈利比"
      tip="注：此账户下全部推广单元的盈利比同步更改"
      :visible.sync="profitOpenVisible"
      @confirm="confirmEarningsMulti"
    ></DialogRatio>

    <!--设置账户曝光数比-->
    <DialogRatio
      title="设置账户曝光数比"
      tip="注：此账户下全部推广单元的曝光数比同步更改"
      :visible.sync="exposureOpenVisible"
      @confirm="confirmExposureMulti"
    ></DialogRatio>

    <!--启用-->
    <DialogConfirm
      :visible.sync="statusOpenVisible"
      :buttons="['启 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusOpen"
      content="是否要启用此账户？"
    ></DialogConfirm>

    <!--停用-->
    <DialogConfirm
      :visible.sync="statusCloseVisible"
      :buttons="['停 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusClose"
      content="是否停用此账户？"
      tip="停用后，账号不能正常登录系统，全部在投广告立刻停止投放！"
    ></DialogConfirm>

    <!--删除账户-->
    <DialogConfirm
      :visible.sync="deleteAccountVisible"
      :buttons="['确定删除', '取 消']"
      :button-primary="[0]"
      @confirm="confirmDeleteAccount"
      content="确定删除此账户？"
    ></DialogConfirm>

    <!--密码重置成功-->
    <Dialog
      :visible.sync="rePasswordDialogVisible"
      :width="350"
      title="密码重置成功"
    >
      <el-form
        align="center"
        class="u-p20"
      >
        <el-form-item class="u-mb0">
          密码：<span class="u-mr10">{{rePasswordDialogText}}</span>
          <el-button
            v-clipboard="rePasswordDialogText"
            type="text"
          >复制</el-button>
        </el-form-item>
        <el-form-item class="u-mb10">
          <Tip>请登录账户后自行修改密码</Tip>
        </el-form-item>
        <el-form-item class="u-mb0">
          <el-button
            type="primary"
            size="small"
            @click="rePasswordDialogVisible = false"
          >关闭</el-button>
        </el-form-item>
      </el-form>
    </Dialog>
  </SectionContainer>
</template>

<script>
import SectionTitle from "@/components/section-title";
import SectionContainer from "@/components/section-container";
import Tip from "@/components/tip";
import Dialog from "@/components/dialog";
import DialogRatio from "@/components/dialog-ratio";
import DialogConfirm from "@/components/dialog-confirm";
import TableFull from "@/components/table-full";
import AuditStatus from "@/components/audit-status";
import AuditStatusItem from "@/components/audit-status-item";

import {
  sessionStorage,
  splitAccount,
  hasPermission,
  getRandomStr
} from "@/utils";
import permissionMixin from "@/mixins/permission";

import {
  fetchAccountSelect,
  fetchAccountCompanySelect,
  fetchAccountList,
  fetchAccountSetEarnings,
  fetchAccountSetExposure,
  fetchAccountGetEarnings,
  fetchAccountGetExposure,
  fetchAccountRestPwd,
  fetchAccountStatus,
  fetchAccountDirectRoleSelect,
  fetchAccountDelete
} from "@/api";

export default {
  mixins: [permissionMixin],
  components: {
    SectionTitle,
    SectionContainer,
    Tip,
    Dialog,
    DialogRatio,
    DialogConfirm,
    TableFull,
    AuditStatus,
    AuditStatusItem
  },
  data() {
    return {
      user: sessionStorage.get("USER"),

      accountOptions: [],
      companyOptions: [],
      roleOptions: [],

      // 筛选
      filter: {
        account: "全部账户",
        company: "全部公司",
        status: 0,
        roleId: ""
      },

      // 分页
      page: {
        pageNo: 1,
        pageSize: 50
      },

      // 弹窗/设置盈利比
      profitOpenVisible: false,
      // 弹窗/设置曝光数比
      exposureOpenVisible: false,
      // 弹窗/历史盈利比
      profitHistoryVisible: false,
      profitHistoryData: [],
      // 弹窗/历史曝光数比
      exposureHistoryVisible: false,
      exposureHistoryData: [],
      // 弹窗/密码重置
      rePasswordDialogText: "DSP123456",
      rePasswordDialogVisible: false,
      // 删除账户
      deleteAccountVisible: false,
      deleteAccountIds: [],

      // 是否启用
      statusKeys: [],
      statusOpenVisible: false,
      statusCloseVisible: false,

      // 表格
      tableData: [],
      tableSelectionData: [],
      tableTotal: 0
    };
  },
  computed: {
    tableColumn() {
      return [
        {
          label: "是否启用",
          prop: "switch",
          visible: hasPermission(["account_advertiser_enable"]),
          width: 55
        },
        {
          label: "账户状态",
          prop: "auditStatus",
          visible: true
        },
        {
          label: "账户名称",
          prop: "accountName",
          visible: true
        },
        {
          label: "登录账号",
          prop: "userName",
          visible: true
        },
        {
          label: "公司名称",
          prop: "company",
          visible: true
        },
        {
          label: "账户余额(元)",
          prop: "amount",
          visible: true
        },
        {
          label: "账户盈利比",
          prop: "profitPercentage",
          visible: true
        },
        {
          label: "账户曝光数比",
          prop: "displayPercentage",
          visible: true
        }
      ].filter(col => col.visible);
    },
    // 拼接选中的数据
    checkedTableData() {
      return this.tableSelectionData.map(item => item.userId);
    }
  },
  methods: {
    // 删除账户
    handleDeleteAccount() {
      return fetchAccountDelete({
        query: {
          ids: this.deleteAccountIds.join()
        }
      });
    },
    // 删除账户/打开弹窗
    openDeleteAccount(ids) {
      this.deleteAccountIds = ids;
      this.deleteAccountVisible = true;
    },
    // 删除账户/确认删除
    confirmDeleteAccount(index) {
      if (index === 0) {
        this.handleDeleteAccount().then(() => {
          this.$message({
            message: "删除成功",
            duration: 1000
          });
          this.deleteAccountVisible = false;
          this.getTable();
        });
      } else {
        this.deleteAccountVisible = false;
      }
    },
    // 是否启用
    openStatus(keys, status) {
      this.statusKeys = keys;
      if (status === 1) {
        this.statusCloseVisible = true;
      } else if (status === 2) {
        this.statusOpenVisible = true;
      }
    },
    // 是否启用/切换状态
    changeStatus(keys, value) {
      return fetchAccountStatus({
        query: {
          ids: keys.join(),
          status: value
        }
      }).then(() => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
      });
    },
    // 是否启用/确认启用
    confirmStatusOpen(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 2).then(() => {
          this.statusOpenVisible = false;
          this.getTable();
        });
      } else {
        this.statusOpenVisible = false;
      }
    },
    // 是否启用/确认停用
    confirmStatusClose(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 1).then(() => {
          this.statusCloseVisible = false;
          this.getTable();
        });
      } else {
        this.statusCloseVisible = false;
      }
    },

    // 广告主角色
    fetchAccountDirectRoleSelect() {
      fetchAccountDirectRoleSelect().then(res => {
        this.roleOptions = [
          {
            name: "全部角色",
            id: ""
          }
        ].concat(res.data.list || []);
        // 默认角色
        if (this.$route.query.roleId) {
          this.filter.roleId = Number(this.$route.query.roleId);
        }
      });
    },
    // 历史盈利比
    fetchAccountGetEarnings(userId) {
      this.profitHistoryData = [];
      fetchAccountGetEarnings({
        query: {
          userId
        }
      }).then(res => {
        this.profitHistoryData = res.data.data;
      });
    },
    // 历史曝光数比
    fetchAccountGetExposure(userId) {
      this.exposureHistoryData = [];
      fetchAccountGetExposure({
        query: {
          userId
        }
      }).then(res => {
        this.exposureHistoryData = res.data.data;
      });
    },
    // 账户下拉
    fetchAccountSelect() {
      fetchAccountSelect().then(res => {
        this.accountOptions = [
          {
            name: "全部账户"
          }
        ].concat(res.data);
      });
    },
    // 公司下拉
    fetchAccountCompanySelect() {
      fetchAccountCompanySelect().then(res => {
        this.companyOptions = [
          {
            company: "全部公司"
          }
        ].concat(res.data);
      });
    },
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 获取表格数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      fetchAccountList({
        body: {
          ...this.page,
          status: this.filter.status,
          roleId: this.filter.roleId || Number(this.$route.query.roleId) || 0,
          account:
            this.filter.account === "全部账户"
              ? ""
              : splitAccount(this.filter.account).name,
          company: this.filter.company === "全部公司" ? "" : this.filter.company
        }
      }).then(res => {
        this.tableData = res.data.dataList || [];
        this.tableTotal = res.data.dataListCount;
      });
    },
    // 表格多选
    tableSelectionChange(val) {
      this.tableSelectionData = val;
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    },
    // 获取内部审核状态title
    getInnerStatusTitle(v) {
      if (v.indexOf("已通过") !== -1) {
        return "<i class='el-icon-success c-hint-succ'></i> 内部审核";
      } else if (v.indexOf("审核拒绝") !== -1) {
        return "<i class='el-icon-warning c-hint-error'></i> 内部审核";
      }
      return "<i class='el-icon-question c-hint-warn'></i> 内部审核";
    },
    // 重置密码
    handleResetPassword(userId) {
      fetchAccountRestPwd({
        query: {
          userId
        }
      }).then(() => {
        this.rePasswordDialogVisible = true;
      });
    },
    // 进入账户
    handleEnterAccount(userId) {
      window.open(`/#/jump/${getRandomStr(8)}${userId}${getRandomStr(8)}`);
    },
    // 批量设置盈利比
    openEarningsMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择账户",
          duration: 2000
        });
      }
      this.profitOpenVisible = true;
    },
    confirmEarningsMulti(ratio) {
      fetchAccountSetEarnings({
        query: {
          userId: this.user.userId,
          ids: this.checkedTableData.join(),
          ratio: ratio
        }
      }).then(() => {
        this.profitOpenVisible = false;
        this.getTable();
      });
    },
    // 批量设置曝光数比
    openExposureMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择账户",
          duration: 2000
        });
      }
      this.exposureOpenVisible = true;
    },
    confirmExposureMulti(ratio) {
      fetchAccountSetExposure({
        query: {
          userId: this.user.userId,
          ids: this.checkedTableData.join(),
          ratio: ratio
        }
      }).then(() => {
        this.exposureOpenVisible = false;
        this.getTable();
      });
    }
  },
  created() {
    this.fetchAccountSelect();
    this.fetchAccountCompanySelect();
    this.fetchAccountDirectRoleSelect();
    this.getTable();
  }
};
</script>
